package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.domain.LongCart;
import org.csu.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/longcart")
public class LongCartServlet extends HttpServlet {
    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从数据库获取list的id
        CatalogService catalogService = new CatalogService();
        Account account = (Account) req.getSession().getAttribute("account");
         Cart cart = new Cart();

        List<LongCart> longCarts = catalogService.findinlongcart(account.getUsername());
        for (LongCart longCart : longCarts) {
            boolean isInStock = catalogService.isItemInStock(longCart.getItemID());
            Item item = catalogService.getItem(longCart.getItemID());
            cart.addItem(item, isInStock);
            cart.setQuantityByItemId(longCart.getItemID(),longCart.getQuantity());
        }
        req.getSession().setAttribute("cart", cart);
        req.getRequestDispatcher(VIEW_CART).forward(req, resp);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
